const http = require('http')
const url = require('url')

const jsonFn = obj => JSON.stringify(obj)

// 允许你跨域的域名
const allowDomain = [
  'http://localhost:4000',
  'http://localhost:5500'
]


http.createServer((req, res) => {

  // console.log(req.headers);

  let user = {
    id: 1,
    name: '张三'
  }
  // 通过设置响应头信息，来允许ajax跨域请求
  // * 表示允许所有域名来跨域请求 
  // * 如果你所写为 * 则cookie将无法跨域
  if (allowDomain.includes(req.headers.origin)) {
    // res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4000')
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin)
    res.setHeader('Access-Control-Allow-Credentials', 'true')
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
    res.setHeader('Access-Control-Allow-Headers', 'username')
    res.setHeader('Access-Control-Expose-Headers', 'uuuu')
  }
  res.setHeader('content-type', 'application/json;charset=utf-8')
  res.setHeader('uuuu', 'admin888')
  res.end(jsonFn(user))

}).listen(3000)


